﻿using System;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using YYTea.MOdel.Dto;
using YYTea.MOdel.Model;
using YYTea.Services.IServices;
using YYTea.Services.VModel;

namespace YYTea.Miljy.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ShoppingCarControllers : ControllerBase
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IShoppingCar _shoppingCar;
        private readonly UserManager<UserInfo> _userManager;

        public ShoppingCarControllers(IHttpContextAccessor httpContextAccessor, IShoppingCar shoppingCar, UserManager<UserInfo> userManager)
        {
            _httpContextAccessor = httpContextAccessor;
            _shoppingCar = shoppingCar;
            _userManager = userManager;
        }
        [HttpGet]
        [Authorize(AuthenticationSchemes = "Bearer")]
        [AllowAnonymous]
        public async Task<IActionResult> GetShoppingCar(string UserID)
        {
            //获取当前用户
            //var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            //var user = _userManager.GetUserId(HttpContext.User);
            if(UserID == null)
            {
                return BadRequest("无当前用户");
            }
            //使用用户Id获取购物车
            var shop = await _shoppingCar.GetShoppingCarById(UserID);

            return Ok(shop);
        }


        [HttpPost]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> AddProductToShoppingCar(ShoppingCarVModel shopVM, string ID)
        {
            //获取当前用户
            //var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            //shopVM.UserId = userId;
            //将物品添加到购物车
            //var shop = await _shoppingCar.GetShoppingCarById(userId);
            if (ID == null)
            {
                return BadRequest(null);
            }
            var shop = await _shoppingCar.AddProducrToShop(shopVM, ID);
            return Ok("添加成功");
        }

        [HttpDelete]
        public async Task<IActionResult> DeleteShoppingCarProduct(Guid Id)
        {
            if (Id == null)
                return NotFound("无此类商品");
            var delete = await _shoppingCar.DeleteShoppingCarProductById(Id);
            return Ok(delete + "已删除");
        }

    }
}
